package com.ljdemo.lrecorder.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.ljdemo.lrecorder.R;
import com.ljdemo.lrecorder.utils.FileUtil;

import java.io.File;
import java.io.IOException;

/**
 * 录屏服务
 * <br/>
 * 创建日期 : 2023/2/16
 * 修改日期 : 2023/9/19
 * */
public class ScreenRecordService extends Service {

    private MediaRecorder mediaRecorder;
    private VirtualDisplay virtualDisplay;
    private MediaProjection mediaProjection;
    private MediaProjectionManager mediaProjectionManager;
    private int DISPLAY_WIDTH=720;
    private int DISPLAY_HEIGHT=1280;
    private boolean audioIsOn =true;// 是否开启声音
    private static final String TAG="录屏服务";
    private int mResultType;
    private int mResultCode;
    private int mResultScreenDensity;
    private Intent mResultData;
    private String savePath;//保存目录
    private final int notification_request_code =1000;// 通知请求码
    private final int notification_id=2000;// 通知ID
    private final String screen_record_name="ScreenRecordNotification";// 通知名

    public static Boolean isRecording=false;

    public ScreenRecordService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    public class  ScreenRecordBinder extends Binder{
        public ScreenRecordService getScreenRecordService(){
            return ScreenRecordService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new ScreenRecordBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // 应用内部目录
        savePath=getExternalFilesDir(Environment.DIRECTORY_MOVIES).toString()+ File.separator;
        Log.i(TAG,"录屏文件输出："+savePath);

        createNotificationChannel();
        mResultType=intent.getIntExtra("type",-1);
        mResultCode=intent.getIntExtra("code",-1);
        mResultScreenDensity=intent.getIntExtra("density",-1);
        mResultData=intent.getParcelableExtra("data");
        DISPLAY_WIDTH=intent.getIntExtra("width",0);
        DISPLAY_HEIGHT=intent.getIntExtra("height",0);

        audioIsOn =intent.getBooleanExtra("audio",true);

        if (mResultType==0){
            //开启录屏
            initRecorder();
            mediaProjectionManager=(MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            mediaProjection=mediaProjectionManager.getMediaProjection(mResultCode,mResultData);
            recordScreen();
        }else if (mResultType==1){
            //取消录屏
            NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.cancel(888);
            stopForeground(true);
            stopRecord();
        }else {//无
            Log.e(TAG,"mResultType没有数据");
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    private void createNotificationChannel(){
        // 获取一个Notification构造器
        Notification.Builder builder=new Notification.Builder(this.getApplicationContext());
        // 点击后跳转的界面，可以设置跳转数据
        Intent nfIntent=new Intent(this,ScreenRecordService.class);

        // 设置PendingIntent（显示在通知栏）
        builder.setContentIntent(PendingIntent.getActivity(this, notification_request_code,nfIntent,PendingIntent.FLAG_IMMUTABLE))
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.icon))
                .setContentTitle("正在录屏")
                .setSmallIcon(R.mipmap.icon)
                .setContentText("正在使用录屏服务")
                .setWhen(System.currentTimeMillis());

        /*以下是对Android 8.0的适配*/
        //普通notification适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            builder.setChannelId(String.valueOf(notification_id));
        }
        //前台服务notification适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationManager notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel=new NotificationChannel(String.valueOf(notification_id),screen_record_name,NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(channel);
        }

        // 获取构建好的Notification
        Notification notification=builder.build();
        // 设置为默认声音
        notification.defaults=Notification.DEFAULT_SOUND;
        startForeground(notification_id,notification);

    }

    /**
     * 初始化录制参数
     * */
    private void initRecorder(){
        try {
            mediaRecorder=new MediaRecorder();

            // 设置音频源
            if (audioIsOn){
                // 音频源包含麦克风
                mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            }

            //设置视频源
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            //视频输出格式(mp4)
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

            //设置视频格式(h264)
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

            if (audioIsOn){
                //设置音频格式放上面会报错
                //设置音频格式(aac)
                mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            }

            String videoFile=savePath+ FileUtil.getFlagName()+".mp4";
            //设置输出文件
            mediaRecorder.setOutputFile(videoFile);
            //设置分辨率
            mediaRecorder.setVideoSize(DISPLAY_WIDTH,DISPLAY_HEIGHT);

            //设置帧率，人体最大30帧
            mediaRecorder.setVideoFrameRate(16);
            //设置视频清晰度（比特率） 8*分辨率
            mediaRecorder.setVideoEncodingBitRate(8*DISPLAY_WIDTH*DISPLAY_HEIGHT);
            mediaRecorder.prepare();
        } catch (IOException e) {
            Log.e(TAG,"mediaRecorder配置异常"+e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 开始录制
     * */
    private void recordScreen(){
        virtualDisplay=mediaProjection.createVirtualDisplay("ScreenRecorder",
                DISPLAY_WIDTH,DISPLAY_HEIGHT,mResultScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,mediaRecorder.getSurface(),
                null,null);
        mediaRecorder.start();
        isRecording=true;
    }

    /**
     * 停止录制
     * */
    private void stopRecord(){
        mediaRecorder.stop();
        mediaRecorder.reset();
        if (virtualDisplay==null){
            return;
        }
        virtualDisplay.release();
        //释放录制资源
        if (mediaProjection!=null){
            mediaProjection.stop();
            mediaProjection=null;
        }
        isRecording=false;
        // 关闭服务
        stopSelf();
    }

}